﻿using Infrastructure.Model;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace Dao
{
    public class DBConfig
    {
        public static string? aaa = ConfigurationManagerModel.Configuration?.GetConnectionString("mysql");

        public static SqlSugarClient GetDb(string? connstr = default)
        {
            connstr ??= aaa;

            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connstr,
                DbType = DbType.MySql,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    EntityNameService = (type, entity) =>
                    {
                        if (type.Name.EndsWith("Entity"))
                        {
                            entity.DbTableName = type.Name[..^6];
                            entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName);//ToUnderLine驼峰转下划线
                        }
                    },
                    EntityService = (t, column) =>
                    {
                        column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName);//ToUnderLine驼峰转下划线
                        
                        string colName = column.DbColumnName;

                        if (colName == "id") //是id的设为主键
                        {
                            column.IsPrimarykey = true;
                        }
                    }
                }
            });

            db.Aop.OnLogExecuting = (sql, pars) =>
            {
#if DEBUG
                Console.WriteLine(sql);
               // ServerContext.Obj.Log.Info(sql + "\r\n" +
              //   db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
#endif
            };
            db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完
            {
#if DEBUG

              //  ServerContext.Obj.Log.Info(db.Ado.SqlExecutionTime.ToString());//输出SQL执行时间
#endif
            };
            db.Aop.OnError = (exp) =>//SQL报错
            {
               // ServerContext.Obj.Log.Error(db.Ado.SqlExecutionTime.ToString());//输出SQL执行时间         
            };
            return db;
        }
    }
}
